package com.vmware.elastic.high;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;

/**
 * @apiNote 高亮查询
 */
public class DocumentHighLightQuery {
    public static void main(String[] args) throws Exception{
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );
        SearchRequest request = new SearchRequest("vmware");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "wangwu");//注意:高亮不支持中文
        searchSourceBuilder.query(termQueryBuilder);
        //构建高亮查询
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<fort style='color:red'>");//设置前缀标签
        highlightBuilder.postTags("</fort>");//设置后缀标签
        highlightBuilder.field("name");//设置高亮字段
        searchSourceBuilder.highlighter(highlightBuilder);

        request.source(searchSourceBuilder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();//获取查询结果
        TimeValue took = response.getTook(); //获取响应时间
        System.out.println("响应时间:" + took);
        for (SearchHit hit : hits) {
            System.out.println(hit);//<fort style='color:red'>wangwu</fort>
        }
        client.close();
    }
}
